<style>
    .Student_information {
        margin-top: 25px;
    }

    .head {
        display: flex;
        justify-content: space-between;
        height: 38px;
        line-height: 38px;
    }
</style>
<div class="Student_information layui-container">
    <!-- 学生信息头部 -->
    <div class="head">
        <h3><strong>管理员信息查看与修改</strong></h3>
    </div>
    <!-- 分割线 -->
    <div>
        <hr class="layui-border-black">
    </div>
    <form action="" class="layui-form" style="margin-top: 20px;">
        <div class="layui-form-item">
            <label class="layui-form-label">用户名</label>
            <div class="layui-input-block">
                <input type="text" name="userName" autocomplete="off" class="layui-input" value="用户名" id="userName-input-text">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">姓名</label>
            <div class="layui-input-block">
                <input type="text" name="fullName" autocomplete="off" class="layui-input" value="姓名" id="fullName-input-text">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">角色</label>
            <div class="layui-input-block">
                <input type="text" name="role" autocomplete="off" class="layui-input" value="角色" id="role-input-text">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
<!--                <button class="layui-btn" lay-submit="" lay-filter="save">立即修改</button>-->
                <button class="layui-btn" type="button" id="reset-password-btn">重置密码</button>
            </div>
        </div>
    </form>
    <!-- 分割线 -->
    <div>
        <hr class="layui-border-black">
    </div>
    <!-- 学生相册信息 -->
    <h3><strong>所管理的专业表</strong></h3>
    <script type="text/html" id="InstoolbarDemo">
        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 增加管理专业权限 </button>
            <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="delete">删除所选专业权限 </button>
        </div>
    </script>
    <table class="layui-hide" id="InsTableId" lay-filter="InsTableFilter"></table>
</div>

<script>
    layui.use(['form', 'layedit', 'laydate','table','miniPage','element'], function() {
        var form = layui.form,
            layer = layui.layer,
            layedit = layui.layedit,
            laydate = layui.laydate,
            table=layui.table,
            miniPage = layui.miniPage;


        //辅导员信息获取
        var userData;
        var userId=localStorage.getItem("selectedInstructorId");
        jq1111.ajax({
            type: "GET",
            async:false,
            crossDomain:true,
            url: BasePath+"api/Account/"+userId,
            contentType: "application/json",
            xhrFields: {
                withCredentials: true
            },
            success:function (message) {
                console.log(message);
                userData=message.data;
                layer.msg(message.msg, function () {
                });
            },
            error:function (message) {
                console.log(message.responseJSON);
                layer.msg('失败:'+message.responseJSON.msg);
            },
        });
        //赋初值
        jq1111('#userName-input-text').val(userData.userName);
        jq1111('#fullName-input-text').val(userData.fullName);
        jq1111('#role-input-text').val(function (){
            var result="";
            var roles= userData.roles;
            roles.forEach(function (role) {
                result+=role;
                result+=" ";
            })
            return result;
        });

        //监听提交
        form.on('submit(save)', function(data) {
            jq1111.ajax({
                type: "POST",
                crossDomain:true,
                url: BasePath+"api/Account/UpdateStudentInfo",
                contentType: "application/json",
                dataType:"json",
                xhrFields: {
                    withCredentials: true
                },
                data:JSON.stringify(
                    {
                        "classId":jq1111('#class-select').val(),
                        "userId": userId
                    }
                ),
                success:function (message) {
                    console.log(message);
                    layer.msg(message.msg, function () {
                    });
                },
                error:function (message) {
                    console.log(message.responseJSON);
                    layer.msg('失败:'+message.responseJSON.msg);
                },
            });
            return false;
        });


        /**
         * 初始化表单，要加上，不然刷新部分组件可能会不加载
         */
        form.render();


        //权限表相关js
        table.render({
            elem: '#InsTableId',
            url:BasePath+'api/Account/'+userId,
            parseData: function(res) { //res 即为原始返回的数据
                console.log(res)
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.managedMajors.length, //解析数据长度
                    "data": res.data.managedMajors //解析数据列表
                };
            },
            toolbar: '#InstoolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [[
                {type: "checkbox", width: 50},
                {field: 'id', width: 80, title: 'ID'},
                {field: 'name', width: 280, title: '专业'},
            ]],
            limits: [10, 15, 20, 25, 50, 100],
            limit: 15,
            page: true,
            skin: 'line'
        });

        //toolbar事件监听
        table.on('toolbar(InsTableFilter)', function (obj) {
            if (obj.event === 'delete') {   // 监听添加操作
                var checkStatus = table.checkStatus('InsTableId')
                    , data = checkStatus.data;
                if (data.length === 0) {
                    layer.alert('未选择要删除的数据', {
                        title: '操作不合法'
                    });
                    return;
                }
                var deletedItemCount = 0;
                data.forEach(function(deleteData) {
                    if (deleteManageedMajor(deleteData.id)) {
                        deletedItemCount++;
                    }
                });
                layer.alert('成功删除' + deletedItemCount + '个数据,' + (data.length - deletedItemCount) + '条删除失败，如果存在删除失败，请尝试刷新界面重试', {
                    title: '操作结果'
                });
                table.reload('InsTableId', {}, 'data');
            }
            else if(obj.event === 'add'){
                var content = miniPage.getHrefContent('page/admin/manageInstructorAccount/add-major.html');
                var openWH = miniPage.getOpenWidthHeight();
                localStorage.setItem("selectedUserId",userId);

                var index = layer.open({
                    title: '添加用户',
                    type: 1,
                    shade: 0.2,
                    maxmin:true,
                    shadeClose: true,
                    area: [openWH[0] + 'px', openWH[1] + 'px'],
                    offset: [openWH[2] + 'px', openWH[3] + 'px'],
                    content: content,
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
            }
        });


        function deleteManageedMajor(id) {
            var result=false;
            jq1111.ajax({
                url:BasePath+"api/Account/DeleteManagedMajor",
                async:false,
                type:"POST",
                contentType: "application/json",
                dataType:"json",
                xhrFields: {
                    withCredentials: true
                },
                data:JSON.stringify({
                    "majorId": id,
                    "userId": userId
                }),
                success:function (message) {
                    result=true;
                },
                error:function (message) {
                    result=false;
                    console.log(message.responseJSON);
                }
            });
            return result;

        }

        //重置密码事件

        jq1111("#reset-password-btn").click(resetPassword);

        function resetPassword() {
            layer.prompt({
                formType: 2,
                value: '',
                title: '请输入新的密码',
            }, function (value, index, elem) {
                console.log('new password', value)
                jq1111.ajax({
                    type: "POST",
                    crossDomain: true,
                    url: BasePath + "api/Account/PassWord/Reset",
                    contentType: "application/json",
                    dataType: "json",
                    xhrFields: {
                        withCredentials: true
                    },
                    data: JSON.stringify(
                        {
                            "NewPassword": value,
                            "id": userId
                        }
                    ),
                    success: function (message) {
                        console.log(message);
                        layer.msg(message.msg, function () {
                        });
                    },
                    error: function (message) {
                        console.log(message.responseJSON);
                        layer.msg('失败:' + message.responseJSON.msg);
                    },
                });

                layer.close(index);
            });
        }

    });
</script>